package com.aacar.controller;

import com.aacar.utils.*;
import com.alipay.config.AlipayConfig;
import com.aacar.dto.Header;
import com.aacar.dto.UserIntegralPayDto;
import com.aacar.entity.OrderPay;
import com.aacar.interceptor.MemLoginKeyValid;
import com.aacar.service.OrderPayService;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.param.AsynCallBackParam;
import com.tencent.common.XMLParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Controller
@RestController
@RequestMapping("/payorder")
public class OrderPayController extends ValidController {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
    
	@Resource
	private OrderPayService orderPayService;

	@Autowired
	private  HttpServletRequest request;

	private boolean callbackValid(HttpServletRequest request) throws Exception{
		//获取支付宝POST过来反馈信息
		Map<String,String> params = new HashMap<String,String>();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			params.put(name, valueStr);
		}
		return AlipaySignature.rsaCheckV1(params, AlipayConfig.ali_public_key, AlipayConfig.input_charset,"RSA2");

	}


	/**
	 * 用户积分充值生成支付宝支付串
	 * @param userIntegralPayDto
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/gen_alipay_paystr_order_uip/0", method = RequestMethod.POST)
	@ResponseBody
	@MemLoginKeyValid
	public Object genAlipayPayStrOrderUIP(@RequestBody UserIntegralPayDto userIntegralPayDto) throws Exception{
		logger.info("request:/payorder/gen_alipay_paystr_order_uip/0" + JSONObject.toJSONString(userIntegralPayDto));
		Header mobileHead = super.getMobileHead(request);
		userIntegralPayDto.setUserId(Long.valueOf(mobileHead.getUserId()));
		String genAliPayStr = orderPayService.genAlipayPayStrOrderUIP(userIntegralPayDto);

		return ResultInfoUtil.setSuccessInfo(genAliPayStr, mobileHead.getService());
	}

	/**
	 * 用户积分充值生成微信支付串
	 * @param userIntegralPayDto
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/gen_weixin_paystr_order_uip/0", method = RequestMethod.POST)
	@ResponseBody
	@MemLoginKeyValid
	public Object genWeiXinPayStrOrderUIP(@RequestBody UserIntegralPayDto userIntegralPayDto) throws Exception{
		logger.info("request:/payorder/gen_weixin_paystr_order_uip/0" + JSONObject.toJSONString(userIntegralPayDto));
		Header mobileHead = super.getMobileHead(request);
		userIntegralPayDto.setUserId(Long.valueOf(mobileHead.getUserId()));
		String genAliPayStr = orderPayService.genWeiXinPayStrOrderUIP(userIntegralPayDto,request.getRemoteAddr());

		return ResultInfoUtil.setSuccessInfo(genAliPayStr, mobileHead.getService());
	}

	//MOCK-会员充值支付宝回调
	@RequestMapping(value = "/alipay_paycallback_order_uip/mock")
	public Object alipayPayCallBackOrderUIPMock(@RequestBody Map<String,String> params) throws Exception{
		logger.info("request:/payorder/alipay_paycallback_order_uip/mock" + JSONObject.toJSONString(params));
		orderPayService.payCallBackOrderUIP(params);
		return ResultInfoUtil.setSuccessInfo("success");

	}

	/**
	 * 会员充值支付宝回调
	 * @param out_trade_no
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/alipay_paycallback_order_uip/0")
	public void alipayPayCallBackOrderUIP(
			@RequestParam(value = "out_trade_no", required = true) String out_trade_no,
			HttpServletRequest request,
			HttpServletResponse response) throws Exception{
		logger.info("####################################################");
		logger.info("/alipay_paycallback_order_uip/0 支付宝回调");

		Map<String, String> converRequestParamMap = BeanUtil.converRequestParamMap(request.getParameterMap());
		logger.info("request:/payorder/alipay_paycallback_order_uip/0" + JSONObject.toJSONString(converRequestParamMap));

		//获取支付宝POST过来反馈信息
		boolean flag = callbackValid(request);
		String res = "error";
		if(flag){
			orderPayService.payCallBackOrderUIP(converRequestParamMap);
			res = "success";
			logger.info(" ##### 回调交易成功");
		}

		PrintWriter writer = response.getWriter();
		writer.print(res);

	}

	/**
	 * 会员充值微信回调
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/weixin_paycallback_order_uip/0")
	public void weiXinPayCallBackOrderUIP(
			HttpServletRequest request,
			HttpServletResponse response) throws Exception{
		logger.info("####################################################");
		logger.info("request:/weixin_paycallback_order_uip/0 会员充值微信回调");

		String receiveXml = receiveXml(request);
		logger.info("####### receiveXml:" + receiveXml);

		Map<String, String> mapFromXML = XMLParser.getStringMapFromXML(receiveXml);
		if (mapFromXML != null && "SUCCESS".equals(mapFromXML.get("return_code"))) {
			/*
			 * out_trade_no 订单号
			 * trade_no 交易号
			 * buyer_email 账号
			 * notify_time 通知时间-->支付成功时间
			 * total_fee 金额
			 */
			Map<String, String> converRequestParamMap = new HashMap<String, String>();
			converRequestParamMap.put("thirdPayCallBackStr", JSONObject.toJSONString(mapFromXML));
			converRequestParamMap.put("out_trade_no", mapFromXML.get("out_trade_no"));
			converRequestParamMap.put("trade_no", mapFromXML.get("transaction_id"));
			converRequestParamMap.put("buyer_logon_id", mapFromXML.get("openid"));
			Date date = DateUtil.convertStringToDate(DateUtil.defaultPattern3,mapFromXML.get("time_end").toString());
			converRequestParamMap.put("notify_time", DateUtil.date2Str(DateUtil.defaultPattern2,date));
			//金额处理
			Integer total_fee = Integer.valueOf(mapFromXML.get("total_fee"));
			double process_total_fee = total_fee/100.0;
			converRequestParamMap.put("total_amount", String.valueOf(process_total_fee));

			orderPayService.payCallBackOrderUIP(converRequestParamMap);

			String xml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
			response.getWriter().write(xml);

		}

	}



	/**
	 * 生成支付宝支付串-订单支付
	 * @param orderPayDto
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/gen_alipay_paystr_order/0", method = RequestMethod.POST)
	@ResponseBody
	@MemLoginKeyValid
	public Object genAlipayPayStrOrder(@RequestBody OrderPay orderPayDto) throws Exception{
		logger.info("request:/payorder/gen_pay_str_order/0" + JSONObject.toJSONString(orderPayDto));
		Header mobileHead = super.getMobileHead(request);
		orderPayDto.setUserId(Long.valueOf(mobileHead.getUserId()));
		String genAliPayStr = orderPayService.genAlipayPayStrOrder(orderPayDto);

		return ResultInfoUtil.setSuccessInfo(genAliPayStr, mobileHead.getService());
	}

	@RequestMapping(value = "/alipay_paycallback_order/0")
	public void alipayPayCallBackOrder(
			@RequestParam(value = "out_trade_no", required = true) String out_trade_no,
			HttpServletRequest request,
			HttpServletResponse response) throws Exception{
		logger.info("####################################################");
		logger.info("/alipay_paycallback_order/0 支付宝回调");

		Map<String, String> converRequestParamMap = BeanUtil.converRequestParamMap(request.getParameterMap());
		logger.info("request:/payorder/alipay_paycallback/0" + JSONObject.toJSONString(converRequestParamMap));

		//获取支付宝POST过来反馈信息
		boolean flag = callbackValid(request);
		String res = "error";
		if(flag){
			orderPayService.payCallBackOrder(converRequestParamMap);
			res = "success";
			logger.info(" ##### 回调交易成功");
		}

		PrintWriter writer = response.getWriter();
		writer.print(res);

	}

	//MOCK-支付订单回调
	@RequestMapping(value = "/alipay_paycallback_order/mock")
	public Object alipayPayCallBackMock(@RequestBody Map<String,String> params) throws Exception{
		logger.info("request:/payorder/alipay_paycallback_order/mock" + JSONObject.toJSONString(params));
		orderPayService.payCallBackOrder(params);
		return ResultInfoUtil.setSuccessInfo("success");

	}

	/**
	 * 生成支付宝支付串-补差价
	 * @param orderPayDto
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/gen_alipay_paystr_bu_order/0", method = RequestMethod.POST)
	@ResponseBody
	@MemLoginKeyValid
	public Object genAlipayPayStrBUOrder(@RequestBody OrderPay orderPayDto) throws Exception{
		logger.info("request:/payorder/gen_alipay_paystr_bu_order/0" + JSONObject.toJSONString(orderPayDto));
		Header mobileHead = super.getMobileHead(request);
		orderPayDto.setUserId(Long.valueOf(mobileHead.getUserId()));
		String genAliPayStr = orderPayService.genAlipayPayStrBUOrder(orderPayDto);

		return ResultInfoUtil.setSuccessInfo(genAliPayStr, mobileHead.getService());
	}



	/**
	 * 生成微信支付订单
	 * @param orderPayDto
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/gen_weixin_paystr_order/0", method = RequestMethod.POST)
	@ResponseBody
	@MemLoginKeyValid
	public Object genWeixinPayStr(@RequestBody OrderPay orderPayDto) throws Exception{
		logger.info("request:/payorder/gen_weixin_str_order/0" + JSONObject.toJSONString(orderPayDto));
		Header mobileHead = super.getMobileHead(request);
		orderPayDto.setUserId(Long.valueOf(mobileHead.getUserId()));
		String genWeixinStr = orderPayService.genWeixinPayStr(orderPayDto, request.getRemoteAddr());
		return ResultInfoUtil.setSuccessInfo(genWeixinStr, mobileHead.getService());
	}


	/**
	 * 微信支付回调
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/weixin_paycallback_order/0")
	public void weiXinPayCallBackOrder(HttpServletRequest request,
									   HttpServletResponse response) throws Exception {
		logger.info("####################################################");
		logger.info("request:/weixin_paycallback_order/0 微信支付回调");

		String receiveXml = receiveXml(request);
		logger.info("####### receiveXml:" + receiveXml);

		Map<String, String> mapFromXML = XMLParser.getStringMapFromXML(receiveXml);
		if (mapFromXML != null && "SUCCESS".equals(mapFromXML.get("return_code"))) {
			/*
			 * out_trade_no 订单号
			 * trade_no 交易号
			 * buyer_email 账号
			 * notify_time 通知时间-->支付成功时间
			 * total_fee 金额
			 */
			Map<String, String> converRequestParamMap = new HashMap<String, String>();
			converRequestParamMap.put("thirdPayCallBackStr", JSONObject.toJSONString(mapFromXML));
			converRequestParamMap.put("out_trade_no", mapFromXML.get("out_trade_no"));
			converRequestParamMap.put("trade_no", mapFromXML.get("transaction_id"));
			converRequestParamMap.put("buyer_logon_id", mapFromXML.get("openid"));
			Date date = DateUtil.convertStringToDate(DateUtil.defaultPattern3,mapFromXML.get("time_end").toString());
			converRequestParamMap.put("notify_time", DateUtil.date2Str(DateUtil.defaultPattern2,date));

			orderPayService.payCallBackOrder(converRequestParamMap);

			String xml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
			response.getWriter().write(xml);

		}
	}

	private String receiveXml(HttpServletRequest request) throws Exception {
		String msg = "";
		BufferedReader rd = new BufferedReader(new InputStreamReader(request.getInputStream()));
		StringBuffer sb = new StringBuffer();
		int ch;
		while ((ch = rd.read()) > -1) {
			sb.append((char) ch);
		}
		msg = sb.toString().trim();
		rd.close();
		return msg;
	}


}
